package hy.client;

import java.io.IOException;
import java.io.InputStream;

public class CmdProcessor {	
	
	public void process(String[] cmd){
		String osName = (System.getProperty("os.name"));
		//windows系统的判定
		if(osName.length() > 7){
			osName = osName.substring(0,7);
		}
		
		System.out.println(osName);
		String[] rCmd = repairCMD(cmd);
		if(osName.equalsIgnoreCase("linux")){
			linuxGO(cmd);
		}
		else if(osName.equalsIgnoreCase("mac")){
			return ;
		}
		else if(osName.equalsIgnoreCase("Windows")){
			windowsGO(cmd);
		}
	}
	
	//对命令的格式进行修复和调整
		private String[] repairCMD(String[] cmd){
			
			
			return cmd;
		}
		
		//执行命令
		private static boolean windowsGO(String[] cmd){
			Process process;
			boolean flag = false;
			InputStream std = null,err = null;
			try {
				process = Runtime.getRuntime().exec(cmd);
				std = process.getInputStream();
				err = process.getErrorStream();
				int i;
				while((i = std.read()) != -1){
					System.out.print((char)i);
				}
				System.out.println();
				while((i = err.read()) != -1){
					System.out.print((char)i);
				}
				System.out.println();
				//命令返回码为0，执行成功了
				if(process.waitFor() == 0)
					flag  = true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					std.close();
					err.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			return flag;
		}
		
		private boolean linuxGO(String[] cmd){
			Process process;
			boolean flag = false;
			InputStream std = null,err = null;
			try {
				process = Runtime.getRuntime().exec(cmd);
				std = process.getInputStream();
				err = process.getErrorStream();
				int i;
				while((i = std.read()) != -1){
					System.out.print((char)i);
				}
				System.out.println();
				while((i = err.read()) != -1){
					System.out.print((char)i);
				}
				System.out.println();
				//命令返回码为0，执行成功了
				if(process.waitFor() == 0)
					flag  = true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					std.close();
					err.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			return flag;
		}
}